<template>
  <div class="app-container" id="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="创建人用户ID" prop="userId">-->
<!--        <el-input-->
<!--          v-model="queryParams.userId"-->
<!--          placeholder="请输入创建人用户ID"-->
<!--          filterable clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="创建人部门ID" prop="deptId">-->
<!--        <el-input-->
<!--          v-model="queryParams.deptId"-->
<!--          placeholder="请输入创建人部门ID"-->
<!--          filterable clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="备忘标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入备忘标题"
          filterable clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="提醒的精确时间" prop="remindTime">
        <el-date-picker filterable clearable
          v-model="queryParams.remindTime"
          type="datetime"
          value-format="yyyy-MM-dd"
          placeholder="请选择提醒的精确时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="提醒人邮箱" prop="remindEmail">
        <el-input
          v-model="queryParams.remindEmail"
          placeholder="请输入提醒人邮箱"
          filterable clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="提前几天提醒" prop="advanceDays">
        <el-input
          v-model="queryParams.advanceDays"
          placeholder="请输入提前几天提醒"
          filterable clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="创建时间" prop="createdTime">-->
<!--        <el-date-picker filterable clearable-->
<!--          v-model="queryParams.createdTime"-->
<!--          type="date"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          placeholder="请选择创建时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="更新时间" prop="updatedTime">-->
<!--        <el-date-picker filterable clearable-->
<!--          v-model="queryParams.updatedTime"-->
<!--          type="date"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          placeholder="请选择更新时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
      <!-- 更多查询条件-->
      <template v-if="isShowMore">


      </template>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button :icon="isShowMore?'el-icon-d-arrow-right':'el-icon-d-arrow-left'" size="mini" type="warning" @click="isShowMore = !isShowMore">更多查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['memo:reminder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['memo:reminder:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['memo:reminder:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['memo:reminder:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reminderList" @selection-change="handleSelectionChange" stripe :height="tableHeight">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="55" label="序号" align="center" fixed/>
<!--      <el-table-column label="主键" align="center" prop="id" />-->
<!--      <el-table-column label="创建人用户ID" align="center" prop="userId" />-->
<!--      <el-table-column label="创建人部门ID" align="center" prop="deptId" />-->
      <el-table-column label="备忘标题" align="center" prop="title" :show-overflow-tooltip="true" width="150"/>
      <el-table-column label="备忘内容" align="center" :show-overflow-tooltip="true" width="200">
        <template slot-scope="scope">
          {{ formatHtmlContent(scope.row.content) }}
        </template>
      </el-table-column>

      <el-table-column label="备忘类型" align="center" prop="memoType">
        <template #default="scope">
          <el-tag
            :type="scope.row.memoType === 'birthday' ? 'warning' : 'info'"
            size="mini"
          >
            {{ scope.row.memoType === 'birthday' ? '🎂 生日' : scope.row.memoType }}
          </el-tag>
          <!-- 如果是系统生成的，加个“系统”标签 -->
          <el-tag
            v-if="scope.row.source === 'system'"
            size="mini"
            type="success"
            style="margin-left: 4px;"
          >
            系统
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="提醒的精确时间" align="center" prop="remindTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.remindTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提醒人邮箱" align="center" prop="remindEmail" />
      <el-table-column label="提前几天提醒" align="center" prop="advanceDays" />
<!--      <el-table-column label="是否已发送邮件" align="center" prop="isSent" />-->
      <el-table-column label="是否已发送邮件" align="center" width="180">
        <template #default="scope">
          <el-switch
            v-model="scope.row.isSent"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
          @change="handleSentStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-info"
              @click="handleInfo(scope.row)"
              v-hasPermi="['memo:reminder:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            :disabled="scope.row.source === 'system'"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['memo:reminder:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            :disabled="scope.row.isSent"
            @click="handleSendEmail(scope.row)"
            v-hasPermi="['memo:reminder:send']"
          >发送邮件</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            :disabled="scope.row.source === 'system'"
            @click="handleDelete(scope.row)"
            v-hasPermi="['memo:reminder:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改备忘录提醒对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="68%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
<!--      <el-col :span="8">-->
<!--            <el-form-item label="创建人用户ID" prop="userId">-->
<!--              <el-input v-model="form.userId"  placeholder="请输入创建人用户ID" />-->
<!--            </el-form-item>-->
<!--      </el-col>-->
<!--      <el-col :span="8">-->
<!--            <el-form-item label="创建人部门ID" prop="deptId">-->
<!--              <el-input v-model="form.deptId"  placeholder="请输入创建人部门ID" />-->
<!--            </el-form-item>-->
<!--      </el-col>-->
      <el-col :span="8">
            <el-form-item label="备忘标题" prop="title">
              <el-input v-model="form.title"  placeholder="请输入备忘标题" />
            </el-form-item>
      </el-col>
          <el-col :span="8">
          <el-form-item label="备忘类型" prop="memoType">
            <el-select v-model="form.memoType" placeholder="请选择类型">
              <el-option label="待办事项" value="todo" />
              <el-option label="生日提醒" value="birthday" />
              <el-option label="会议提醒" value="meeting" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>
          </el-col>
      <el-col :span="24">
        <el-form-item label="备忘内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
      </el-col>
          <el-col :span="8">
                <el-form-item label="提醒的精确时间" prop="remindTime">
                  <el-date-picker filterable clearable
                    v-model="form.remindTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="请选择提醒的精确时间">
                  </el-date-picker>
                </el-form-item>
          </el-col>
<!--      <el-col :span="8">-->
<!--            <el-form-item label="提醒人邮箱" prop="remindEmail">-->
<!--              <el-input v-model="form.remindEmail"  placeholder="请输入提醒人邮箱" />-->
<!--            </el-form-item>-->
<!--      </el-col>-->
          <el-col :span="8">
            <el-form-item label="提醒人邮箱" prop="remindEmails">
              <el-select
                v-model="form.remindEmails"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请选择或输入邮箱"
                style="width: 100%;"
              >
                <el-option
                  v-for="emp in empList"
                  :key="emp.email"
                  :label="emp.empName + ' (' + emp.email + ')'"
                  :value="emp.email"
                />
              </el-select>
            </el-form-item>
          </el-col>
      <el-col :span="8">
            <el-form-item label="提前几天提醒" prop="advanceDays">
              <el-input v-model="form.advanceDays"  placeholder="请输入提前几天提醒" />
            </el-form-item>
      </el-col>
<!--          <el-col :span="8">-->
<!--                <el-form-item label="创建时间" prop="createdTime">-->
<!--                  <el-date-picker filterable clearable-->
<!--                    v-model="form.createdTime"-->
<!--                    type="datetime"-->
<!--                    value-format="yyyy-MM-dd"-->
<!--                    placeholder="请选择创建时间">-->
<!--                  </el-date-picker>-->
<!--                </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="8">-->
<!--                <el-form-item label="更新时间" prop="updatedTime">-->
<!--                  <el-date-picker filterable clearable-->
<!--                    v-model="form.updatedTime"-->
<!--                    type="datetime"-->
<!--                    value-format="yyyy-MM-dd"-->
<!--                    placeholder="请选择更新时间">-->
<!--                  </el-date-picker>-->
<!--                </el-form-item>-->
<!--          </el-col>-->
<!--      <el-col :span="8">-->
<!--            <el-form-item label="删除标志：0=正常，2=删除" prop="delFlag">-->
<!--              <el-input v-model="form.delFlag"  placeholder="请输入删除标志：0=正常，2=删除" />-->
<!--            </el-form-item>-->
<!--      </el-col>-->
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 备忘录提醒详情对话框 -->
    <el-dialog :title="title" :visible.sync="openInfo" width="68%" append-to-body>
      <el-descriptions border >
<!--                        <el-descriptions-item label="创建人用户ID" >{{form.userId}}</el-descriptions-item>-->
<!--                        <el-descriptions-item label="创建人部门ID" >{{form.deptId}}</el-descriptions-item>-->
                        <el-descriptions-item label="备忘标题" >{{form.title}}</el-descriptions-item>
                        <el-descriptions-item label="备忘内容" span="3">
                          <div v-html="form.content"/>
                        </el-descriptions-item>
                        <el-descriptions-item label="提醒的精确时间" >
                            {{ parseTime(form.remindTime, '{y}-{m}-{d}')}}
                        </el-descriptions-item>
                        <el-descriptions-item label="提醒人邮箱" >{{form.remindEmail}}</el-descriptions-item>
                        <el-descriptions-item label="提前几天提醒" >{{form.advanceDays}}</el-descriptions-item>
<!--                        <el-descriptions-item label="创建时间" >-->
<!--                            {{ parseTime(form.createdTime, '{y}-{m}-{d} {h}:{i}')}}-->
<!--                        </el-descriptions-item>-->
<!--                        <el-descriptions-item label="更新时间" >-->
<!--                            {{ parseTime(form.updatedTime, '{y}-{m}-{d} {h}:{i}')}}-->
<!--                        </el-descriptions-item>-->
<!--                        <el-descriptions-item label="删除标志：0=正常，2=删除" >{{form.delFlag}}</el-descriptions-item>-->
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReminder, getReminder, delReminder, addReminder, updateReminder, sendReminderEmail } from "@/api/memo/reminder";
import { listEmployee } from "@/api/hrm/employee";

export default {
  name: "Reminder",
  data() {
    return {
      // 是否显示更多
      isShowMore: false,
      // el-table 高度
      tableHeight: 650, // 用于存储 el-table 的高度
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 备忘录提醒表格数据
      reminderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      openInfo: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        deptId: null,
        title: null,
        content: null,
        memoType: null,
        remindTime: null,
        remindEmail: null,
        advanceDays: null,
        isSent: null,
        createdTime: null,
        updatedTime: null,
      },
      // 表单参数
      form: {
        remindEmails: []
      },
      // 表单校验
      rules: {
        title: [
          { required: true, message: "备忘标题不能为空", trigger: "blur" }
        ],
        memoType: [
          { required: true, message: "备忘类型不能为空", trigger: "change" }
        ],
        remindEmail: [
          { required: true, message: "提醒人邮箱不能为空", trigger: "blur" }
        ],
      },
      // 员工列表
      empList: [],
    };
  },
  created() {
    this.getList();
    this.setTableHeight();
    window.addEventListener('resize', this.setTableHeight); // 监听窗口大小变化
    this.getEmpList();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setTableHeight); // 移除事件监听
  },
  methods: {
    formatHtmlContent(html) {
      if (!html) return '';
      const div = document.createElement('div');
      div.innerHTML = html;
      return div.innerText.trim();
    },
    /** 发送邮件按钮操作 */
    handleSendEmail(row) {
      const email = row.remindEmail;
      if (!email) {
        this.$message.warning('该备忘录未设置提醒邮箱');
        return;
      }

      this.$confirm(`确定要向 ${email} 发送备忘提醒邮件吗？`, '发送邮件', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;

        // ✅ 只传 id 即可
        sendReminderEmail(row.id).then(res => {
          this.loading = false;
          if (res.code === 200) {
            this.$message.success('邮件发送任务已提交！');
            this.getList();
          } else {
            this.$message.error('发送失败：' + res.msg);
          }
        }).catch(err => {
          this.loading = false;
          this.$message.error('网络错误，发送失败');
          console.error('邮件发送失败:', err);
        });
      }).catch(() => {
        this.$message.info('已取消发送');
      });
    },
    /** 查询备忘录提醒列表 */
    getList() {
      this.loading = true;
      listReminder(this.queryParams).then(response => {
        this.reminderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openInfo = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        deptId: null,
        title: null,
        content: null,
        memoType: null,
        remindTime: null,
        remindEmail: null,
        advanceDays: null,
        isSent: null,
        createdTime: null,
        updatedTime: null,
        createBy: null,
        updateBy: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加备忘录提醒";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getReminder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改备忘录提醒";
      });
    },
    /** 详情按钮操作 */
    handleInfo(row) {
      this.reset();
      const id = row.id || this.ids
      getReminder(id).then(response => {
        this.form = response.data;
        this.openInfo = true;
        this.title = "备忘录提醒详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // ✅ 关键：把 remindEmails 数组转成逗号分隔的字符串
          if (Array.isArray(this.form.remindEmails)) {
            this.form.remindEmail = this.form.remindEmails.join(',');
          }

          if (this.form.id != null) {
            updateReminder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReminder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除备忘录提醒编号为"' + ids + '"的数据项？').then(function() {
        return delReminder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('memo/reminder/export', {
        ...this.queryParams
      }, `备忘录提醒数据导出_${new Date().getTime()}.xlsx`)
    },
    // 设置表格高度
    setTableHeight() {
      const appContainer = document.getElementById('app-container');
      if (appContainer) {
        this.tableHeight = appContainer.clientHeight * 0.8;
      }
    },
    /** 获取员工信息 */
    getEmpList(){
      listEmployee(
        {
          pageNum: 1,
          pageSize: 10000,
        }).then(response => {
        this.empList = response.rows;
        console.log("empList",this.empList)
      });
    },
    handleSentStatusChange(row) {
      const data = {
        id: row.id,
        isSent: row.isSent ? 1 : 0  // 强制转为 1 或 0
      }
      // 调用更新接口
      updateReminder(data).then(res => {
        if (res.code === 200) {
          this.$message.success(`邮件发送状态已${row.isSent ? '开启' : '关闭'}`)
        } else {
          // 如果失败，回滚状态
          row.isSent = !row.isSent
          this.$message.error('更新失败，请重试')
        }
      }).catch(err => {
        // 请求失败，回滚开关状态
        row.isSent = !row.isSent
        this.$message.error('网络错误，更新失败')
        console.error(err)
      })
    }
  }
};
</script>
